﻿using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Common.Infrastructure.Structs
{
    public class JsonExpressionValueProvider : ExpressionValueProvider, IValueProvider
    {
        private readonly MemberInfo memberInfo;

        public JsonExpressionValueProvider(MemberInfo memberInfo)
            : base(memberInfo)
        {
            this.memberInfo = memberInfo;
        }

        public new object GetValue(object target)
        {
            object obj = base.GetValue(target);
            if (obj == null)
            {
                Type type = null;
                PropertyInfo propertyInfo = memberInfo as PropertyInfo;
                if (propertyInfo != null)
                {
                    type = propertyInfo.PropertyType.GetUnNullableType();
                }

                FieldInfo fieldInfo = memberInfo as FieldInfo;
                if (fieldInfo != null)
                {
                    type = fieldInfo.FieldType.GetUnNullableType();
                }

                if (type != null)
                {
                    obj = GetValueByType(type);
                }
            }

            return obj;
        }

        protected virtual object GetValueByType(Type type)
        {
            object result = null;
            if (type == typeof(decimal))
            {
                result = decimal.Zero;
            }
            else if (type == typeof(int))
            {
                result = 0;
            }
            else if (type == typeof(byte))
            {
                result = (byte)0;
            }
            else if (type == typeof(bool))
            {
                result = false;
            }
            else if (type == typeof(double))
            {
                result = 0.0;
            }

            return result;
        }
    }
}
